import React, { Fragment, useContext, useMemo } from 'react';
import { Alert } from 'antd';
import { MemoContext } from '../useMemo';

export const Memo = () => {
    const { red, blue, yellow } = useContext(MemoContext);

    const formatTime = value => {
        console.group('Memo');
        console.log(`red update at: ${red}`);
        console.log(`blue update at: ${blue}`);
        console.log(`yellow update at: ${yellow}`);
        console.groupEnd();
        const t = new Date(value);
        const y = t.getFullYear();
        const m = t.getMonth() + 1;
        const d = t.getDate();
        const H = t.getHours();
        const M = t.getMinutes();
        const S = t.getSeconds();

        return `${y}年${m}月${d}日 ${H}时${M}分${S}秒`;
    };

    const updateRed = useMemo(() => formatTime(red), [red]);
    const updateBlue = useMemo(() => formatTime(blue), [blue]);
    const updateYellow = useMemo(() => formatTime(yellow), [yellow]);

    return (
        <Fragment>
            <Alert message="useMemo" description={<p>每次更新只会输出一次</p>} type="info" />
            <p>red update at: {updateRed}</p>
            <p>blue update at: {updateBlue}</p>
            <p>yellow update at: {updateYellow}</p>
        </Fragment>
    );
};
